package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.dababases.entity.Orders;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

/**
 * @author suiyu_yang
 * @description Order的Dao
 * @date 2019-06-20 23:38
 * @email suiyu_yang@163.com
 */
public class OrderDao {
    public void insert(Orders orders) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(orders);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(Orders orders) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(orders);

        transaction.commit();
        HibernateUtil.closeSession();

    }

    public void update(Orders orders) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(orders);

        //当事务提交时，hibernate会自动按照一定的策略将session中的持久化对象，同步到数据库中，从而自动使数据库的状态和session中的对象状态完全一致。
        // 如果要在事务提交前同步，则可以使用session的flush方法。
        session.flush();

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public Orders getOrderByOrderId(int orderId) {
        Session session = HibernateUtil.currentSession();

        String sql = "from Orders order where order.id = '" + orderId + "' ";

        Orders orders = (Orders) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return orders;
    }

    public List<Orders> getOrdersByBuyer(Buyer buyer) {
        Session session = HibernateUtil.currentSession();

        String sql = "select * from Orders  where Orders.buyer_id = " + buyer.getId();

        //通过addEntity()方法来实现。addEntity()方法可以讲结果转换为实体
        List<Orders> ordersList = session.createSQLQuery(sql).addEntity(Orders.class).list();
        HibernateUtil.closeSession();

        return ordersList;
    }

}
